package com.tjmc.nsia.core.schedule;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.tjmc.nsia.core.constant.Constants;
import com.tjmc.nsia.core.dao.entity.NsiaChat;
import com.tjmc.nsia.core.dao.entity.NsiaLogininfor;
import com.tjmc.nsia.core.dao.entity.NsiaOperLog;
import com.tjmc.nsia.core.domain.AjaxResult;
import com.tjmc.nsia.core.service.NsiaChatService;
import com.tjmc.nsia.core.service.NsiaLogininforService;
import com.tjmc.nsia.core.service.NsiaOperLogService;
import com.tjmc.nsia.core.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.TimerTask;

/**
 * @author Luc
 * @version 1.0
 * @date 2024-06-06 16:17
 */
public class AsyncFactory {

    private static final Logger logger = LoggerFactory.getLogger(AsyncFactory.class);

    public static TimerTask recordLogininfor(String username, String status, String message, Object... args) {
        UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        return new TimerTask() {
            @Override
            public void run() {
            String address = AddressUtils.getRealAddressByIP(ip);
            StringBuilder s = new StringBuilder();
            s.append(LogUtils.getBlock(ip));
            s.append(address);
            s.append(LogUtils.getBlock(username));
            s.append(LogUtils.getBlock(status));
            s.append(LogUtils.getBlock(message));
            logger.info(s.toString(), args);
            String os = userAgent.getOs().getName();
            String browser = userAgent.getBrowser().getName();
            NsiaLogininfor nsiaLogininfor = new NsiaLogininfor();
            nsiaLogininfor.setUsername(username);
            nsiaLogininfor.setIpaddr(ip);
            nsiaLogininfor.setLoginLocation(address);
            nsiaLogininfor.setBrowser(browser);
            nsiaLogininfor.setOs(os);
            nsiaLogininfor.setMsg(message);
            nsiaLogininfor.setLoginTime(LocalDateTime.now());
            // 日志状态
            if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
                nsiaLogininfor.setStatus(Constants.SUCCESS);
            } else if (Constants.LOGIN_FAIL.equals(status)) {
                nsiaLogininfor.setStatus(Constants.FAIL);
            }
            // 插入数据
            SpringUtils.getBean(NsiaLogininforService.class).save(nsiaLogininfor);
            }
        };
    }


    public static TimerTask recordOper(NsiaOperLog operLog) {
        return new TimerTask() {
            @Override
            public void run() {
            operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
            SpringUtils.getBean(NsiaOperLogService.class).save(operLog);
            }
        };
    }

    public static TimerTask streamResponse(NsiaChat nsiaChat, String employeeCode) {
        return new TimerTask() {
            @Override
            public void run() {
            try {
                String answer = BigmodelUtils.sseInvoke(nsiaChat, employeeCode);
                nsiaChat.setAnswer(answer);
                nsiaChat.setEndTime(LocalDateTime.now());
                NsiaOperLog operLog = SpringUtils.getBean(NsiaOperLogService.class).getByRemark(nsiaChat.getChatId());
                if(!Objects.isNull(operLog)) {
                    operLog.setJsonResult(JSON.toJSONString(AjaxResult.success(nsiaChat)));
                    SpringUtils.getBean(NsiaOperLogService.class).updateById(operLog);
                    SpringUtils.getBean(NsiaChatService.class).save(nsiaChat);
                    logger.info("streamResponse: " + operLog.getJsonResult());
                }
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            }
        };
    }

    public static TimerTask websocketResponse(NsiaChat nsiaChat, String userId) {
        return new TimerTask() {
            @Override
            public void run() {
            try {
                String answer = BigmodelUtils.webSocketInvoke(nsiaChat, userId);
                nsiaChat.setAnswer(answer);
                nsiaChat.setEndTime(LocalDateTime.now());
                NsiaOperLog operLog = SpringUtils.getBean(NsiaOperLogService.class).getByRemark(nsiaChat.getChatId());
                if(!Objects.isNull(operLog)) {
                    operLog.setJsonResult(JSON.toJSONString(AjaxResult.success(nsiaChat)));
                    SpringUtils.getBean(NsiaOperLogService.class).updateById(operLog);
                    SpringUtils.getBean(NsiaChatService.class).save(nsiaChat);
                    logger.info("streamResponse: " + operLog.getJsonResult());
                }
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            }
        };
    }
}
